import axios from 'axios'
import Vue from 'vue'
import store from '../../store/index'

window.config = {
  Host: {
    production: 'http://localhost:6701/',  //开发环境地址
    development: 'http://localhost:30020/',  //生产环境
    test: 'http://10.10.40.66:8080/',      // 测试环境
  },
}

/**
 * 获取一个新的自定义的axios实例
 */
const ajaxUrl =
  process.env.NODE_ENV === 'development'
    ? window.config.Host.development // 开发环境中的后端地址
    : process.env.NODE_ENV === 'production'
    ? window.config.Host.production // 生产环境中的后端地址
    : window.config.Host.test // 测试环境的后端地址

let ajax = axios.create({
  baseURL: ajaxUrl,
  timeout: 30000,
  withCredentials: true
})
let s = new Vue()

ajax.interceptors.request.use(function (request) {
  // 在发送请求之前做些什么
  return request;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

ajax.interceptors.response.use(function(response) {

  return response
}, function(error) {
  return Promise.reject(error);
})

/*
* 封装一个私有的请求方法
*/
const _request = (method, url, data,succ_fuc) => {
  const headers = {}
  const configData = {
    url, // 请求的地址
    headers
  }

  let Data = data;

  if (method === 'get') {
    configData.method = 'get'
    configData.params = Data // get 请求的数据
  } else if (method === 'postForm') {
    configData.method = 'post'
    if (Data instanceof FormData) {
      configData.headers['Content-Type'] = 'multipart/form-data; charset=UTF-8'
      configData.data = Data
    } else {
      configData.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
      configData.data = qs.stringify(Data)
    }
  } else if (method === 'postJson') {
    configData.method = 'post'
    configData.headers['Content-Type'] = 'application/json; charset=UTF-8'
    configData.data = Data
  }

  return ajax(configData).then(response => {
    var data = response.data;
    if(data != null && data != undefined){
      if(!data.isSuccess){
        if (data.errorCode == "5005") {
          window.location.href = "#/login";
        }else{
          store.dispatch('base/showErrorNotify',data.errorMsg);
        }
      }else {
        succ_fuc(data);
      }

    }
  }).catch(error =>{
    store.dispatch('base/showErrorNotify','网络连接异常啦！');
  })
}

class Server {
  get = (url,succ_fuc, data = {}) => {
    return _request('get', url, data,succ_fuc)
  }

  postForm = (url,succ_fuc, data = {}) => {
    return _request('postForm', url, data,succ_fuc)
  }

  postJson = (url,succ_fuc, data = {}) => {
    return _request('postJson', url, data,succ_fuc)
  }

  post = this.postJson // 默认post的Content-Type是application/json
}

export default new Server()

